package com.lihao.walkers.dialog;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Tip;
import com.amap.api.services.help.Inputtips.InputtipsListener;
import com.lihao.walkers.R;
import com.lihao.walkers.fork.OriginActivity;
import com.lihao.walkers.utils.Constants;

/**
 * 搜索任意POI的对话框。
 * @author lihao
 */
public class SearchPOISettingDialog extends OriginActivity implements
		OnClickListener, OnItemSelectedListener, TextWatcher {

	/** 当前纬度。 */
	private double mCurrentLat = -1;

	/** 当前经度。 */
	private double mCurrentLon = -1;

	/** 当前对话框背景。 */
	private ScrollView mBg = null;

	/** 对话框标题。 */
	private TextView mTip = null;

	/** 搜索关键字输入框。 */
	private AutoCompleteTextView mKeyInput = null;

	/** 所在城市提示语。 */
	private TextView mCityTip = null;

	/** 城市列表。 */
	private final List<String> CITY_NAMES = new ArrayList<String>();

	/** 城市选择下拉列表。 */
	private Spinner mCityList = null;

	/** 当前所在城市。 */
	private String mCurrentCity = null;

	/** 确认按钮。 */
	private Button mConfirm = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_poi_setting_layout);
		receiveData();
		initCityNames();
		init();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		if (id == R.id.btnSearchConfirm) {
			String keyWorlds = mKeyInput.getText().toString();
			if(!TextUtils.isEmpty(keyWorlds)){
				Intent intent = new Intent();
				intent.putExtra(Constants.CURRENT_LAT, mCurrentLat);
				intent.putExtra(Constants.CURRENT_LON, mCurrentLon);
				intent.putExtra(Constants.SEARCH_POI_KEY_WORD, keyWorlds);
				intent.putExtra(Constants.SEARCH_POI_KEY_CITY,
						mCurrentCity == null ? "北京": mCurrentCity);
				setResult(Constants.RECEIVE_SEARCH_POI_SETTINGS, intent);
			}
			CITY_NAMES.clear();
			finish();
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
							   long id) {
		mCurrentCity = CITY_NAMES.get(position);
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
								  int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		String newText = s.toString().trim();
		try {
			Inputtips inputTips = new Inputtips(this, new InputtipsListener() {
				@Override
				public void onGetInputtips(List<Tip> tipList, int rCode) {
					if (rCode == 1000){
						List<String> listString = new ArrayList<String>();
						for (int i = 0; i < tipList.size(); i++) {
							listString.add(tipList.get(i).getName());
						}
						ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(
								getApplicationContext(),
								R.layout.route_inputs, listString);
						mKeyInput.setAdapter(aAdapter);
						aAdapter.notifyDataSetChanged();
					}
				}
			});
			inputTips.requestInputtips(newText, mCurrentCity);
		} catch (AMapException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void afterTextChanged(Editable s) {

	}

	/**
	 * 初始化城市列表。
	 */
	private void initCityNames(){
		CITY_NAMES.clear();
		Arrays.sort(Constants.CITY_NAMES, new Comparator<String>() {
			@Override
			public int compare(String object1, String object2) {
				// 对中文单词进行排序。
				return Collator.getInstance(Locale.CHINESE).compare(object1, object2);
			}
		});
		int i = 0;
		int count = Constants.CITY_NAMES.length;
		for (; i < count; i++) {
			CITY_NAMES.add(Constants.CITY_NAMES[i]);
		}
	}

	/**
	 * 接收数据。
	 */
	private void receiveData(){
		Bundle bundle = getIntent().getExtras();
		setScreenWidth(bundle.getInt(Constants.SCREEN_WIDTH));
		setScreenHeight(bundle.getInt(Constants.SCREEN_HEIGHT));
		mCurrentLat = bundle.getDouble(Constants.CURRENT_LAT);
		mCurrentLon = bundle.getDouble(Constants.CURRENT_LON);
	}

	/**
	 * 初始化。
	 */
	private void init(){
		mBg = (ScrollView) findViewById(R.id.svSearchPOIBg);
		FrameLayout.LayoutParams bgLp = (FrameLayout.LayoutParams) mBg.getLayoutParams();
		bgLp.height = (int) (getScreenHeight() * 0.67f);
		mTip = (TextView) findViewById(R.id.tvSearchPOITip);
		mKeyInput = (AutoCompleteTextView) findViewById(R.id.etKey);
		mCityTip = (TextView) findViewById(R.id.tvCityTip);
		mCityList = (Spinner) findViewById(R.id.spCityList);
		mConfirm = (Button) findViewById(R.id.btnSearchConfirm);
		int smallerSize = Math.min(getScreenWidth(), getScreenHeight());

		StringBuffer textInfo = new StringBuffer();
		// 确定tip文字内容。
		textInfo.append(getString(R.string.search_places_like)).append(":");
		mTip.setText(textInfo.toString());
		// 输入框的输入提示。
		mKeyInput.addTextChangedListener(this);
		// 确定所在城市提示语文字内容。
		textInfo.delete(0, textInfo.length());
		textInfo.setLength(0);
		textInfo.append(getString(R.string.search_city_like)).append(":");
		mCityTip.setText(textInfo.toString());
		// 确定城市选择列表内容。
		initCityList();
		// 确定按钮布局。
		RelativeLayout.LayoutParams confirmLp = (LayoutParams) mConfirm.getLayoutParams();
		confirmLp.width = getScreenWidth() >> 2;
		confirmLp.height = (int) (smallerSize * Constants.MAIN_BUTTON_WIDTH);
		mConfirm.setOnClickListener(this);
	}

	/**
	 * 确定城市选择列表的内容。
	 */
	private void initCityList(){
		ArrayAdapter<String> cityNames = new ArrayAdapter<String>(
				this, android.R.layout.simple_spinner_item, CITY_NAMES);
		cityNames.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mCityList.setAdapter(cityNames);
		mCityList.setSelection(CITY_NAMES.indexOf("北京"), true); // 选择默认列。
		mCityList.setOnItemSelectedListener(this);
	}
}
